<?php  
/*
Plugin Name: 广告管理
Plugin URI: https://www.beizigen.com
Description: 支持广告有效期设置，广告到期后将自动下架。
Version: 1.0.0
Author: 背字根
Author URI: https://www.beizigen.com
*/

//创建任务
function bzg_ad_add_cron() {
	$timestamp = current_time('timestamp', 1);
	if( ! wp_next_scheduled( 'ad_cron' ) )
		wp_schedule_event( $timestamp, 'daily', 'ad_cron');
}
register_activation_hook( __FILE__, 'bzg_ad_add_cron' );

//删除任务
function bzg_ad_delete_cron() {
	if( wp_next_scheduled( 'ad_cron' ) ) 
		wp_clear_scheduled_hook( 'ad_cron' );
}
register_deactivation_hook( __FILE__, 'bzg_ad_delete_cron' );
register_uninstall_hook( __FILE__, 'bzg_ad_delete_cron' );

//有效期
function bzg_ad_time( $cycle ) {
	switch ( $cycle ) {
		case 'week': $timestamp = 604800;
			break;
		case 'month': $timestamp = 2592000;
			break;
		case 'quarterly': $timestamp = 7776000;
			break;
		case 'semiannually': $timestamp = 15552000;
			break;
		case 'annually': $timestamp = 31536000;
			break;
		case 'onetime': $timestamp = -1;
			break;
		case 'overdue': $timestamp = 0;
			break;
	}
	return $timestamp;
}

//任务执行函数
function bzg_ad_cron_fun() {
	$ads = get_option( 'ad' );
	$ads = unserialize( $ads );
	if( empty( $ads ) ) return;
	
	foreach( $ads as $k=>$v ) {
		$cycle = $v['cycle'];
		$new_cycle = $cycle;
		
		$cycle_timestamp = bzg_ad_time( $cycle );
		
		if( $cycle != 'onetime' && $cycle != 'overdue' ) {
			if( ( (int) $k + $cycle_timestamp ) < current_time( 'timestamp' ) )
				$new_cycle = 'overdue';
		}
		$data[$k] = array(
			'title' => stripslashes( $v['title'] ),
			'code' => stripslashes( $v['code'] ),
			'cycle' => $new_cycle,
		);
	}
	$data = serialize( $data );
	update_option( 'ad', $data );
}
add_action( 'ad_cron', 'bzg_ad_cron_fun' );

function bzg_ad_updata_options( $groups ) {
	$data = array();
	foreach ( $groups as $g ) {
		$title = 'ad_title_' . $g;
		$code = 'ad_code_' . $g;
		$cycle = 'ad_cycle_' . $g;
		if( isset( $_POST[ $code ] ) && ! empty( $_POST[ $code ] ) ) {
			$data[$g] = array(
				'title' => stripslashes( $_POST[ $title ] ),
				'code' => stripslashes( $_POST[ $code ] ),
				'cycle' => $_POST[ $cycle ],
			);
		}
	}
	$data = serialize( $data );
	update_option( 'ad', $data );
}
function bzg_ad_option( $key, $val ) {
	$var_name_title = 'ad_title_' . $key;
	$var_name_cycle = 'ad_cycle_' . $key;
	$var_name_code = 'ad_code_' . $key;
	
	echo '<tr>
			<th scope="row">
				<label for="' . $var_name_title . '">广告标题</label>
			</th>
			<td>
				<input id="' . $var_name_title . '" name="' . $var_name_title . '" class="regular-text code" type="text" value="' . $val['title'] . '" />
				<p class="description">不会显示在页面，用于区分广告</p>
			</td>
		</tr>
		<tr>
			<th scope="row">
				<label for="' . $var_name_cycle . '">投放时长</label>
			</th>
			<td>
				<select id="' . $var_name_cycle . '" name="' . $var_name_cycle . '">
					<option value="week"' . ( $val['cycle'] == 'week' ? ' selected="selected"' : '' )  . '>一周</option>
					<option value="month"' . ( $val['cycle'] == 'month' ? ' selected="selected"' : '' )  . '>一月</option>
					<option value="quarterly"' . ( $val['cycle'] == 'quarterly' ? ' selected="selected"' : '' )  . '>一季</option>
					<option value="semiannually"' . ( $val['cycle'] == 'semiannually' ? ' selected="selected"' : '' )  . '>半年</option>
					<option value="annually"' . ( $val['cycle'] == 'annually' ? ' selected="selected"' : '' )  . '>一年</option>
					<option value="onetime"' . ( $val['cycle'] == 'onetime' ? ' selected="selected"' : '' )  . '>永久</option>
					<option value="overdue"' . ( $val['cycle'] == 'overdue' ? ' selected="selected"' : '' )  . '>过期</option>
				</select>
				<p class="description">开始时间：' . date( 'Y-m-d H:i:s', $key ) . '</p>
			</td>
		</tr>
		<tr>
			<th scope="row">
				<label for="' . $var_name_code . '">广告代码</label>
			</th>
			<td>
				<textarea name="' . $var_name_code . '" id="' . $var_name_code . '" class="large-text code" rows="5" cols="50">' . $val['code'] . '</textarea>
			</td>
		</tr>';
		if( ! empty( $val['code'] ) )
			echo '<tr><th scope="row">调用代码</th><td><input type="text" class="regular-text code" value="&lt;?php echo bzg_get_ad( \'' . $key . '\' ); //' . $val['title'] . ' ?&gt;" /></td></tr>';
}
function bzg_get_ad( $var ) {
	$ads = get_option( 'ad' );
	$ads = unserialize( $ads );
	$the_ad = '';
	if( ! empty( $ads ) )
		$the_ad = $ads[$var];
	
	if( empty( $the_ad ) || $the_ad['cycle'] == 'overdue' )
		return;
	
	return $the_ad['code'];
}
function bzg_ad_control() {
	
	if( isset( $_POST['action'] ) && $_POST['action'] == 'save' ) {
		$ads = get_option( 'ad' );
		$ads = unserialize( $ads );
		$ad_keys = array();
		if( ! empty( $ads ) )
			$ad_keys = array_keys( $ads );
		$add_key = $_POST['new_key'];
		array_push( $ad_keys, $add_key );
		bzg_ad_updata_options( $ad_keys );
		bzg_ad_add_sync_cron();
		echo '<div id="message" class="updated fade">保存成功！</div>';
	}

?>
<style type="text/css">
#message {
	padding: .8em;
	margin: 1em 0;
}
.form-table {
	background-color: #ffffff;
	border-collapse: separate;
	padding: 1em;
	margin: 1em 0;
	box-shadow: 0 0 3px #cecece;
	border-radius: 4px;
	border: 1px solid #cecece;
}
.form-table:hover {
	border: 1px solid #0073aa;
}
.overdue {
	opacity: .7;
}
.overdue:hover {
	border: 1px solid #cecece;
}
.form-table td, .form-table th {
	padding: .3em 0;
	font-weight: normal;
}
#generate-code {
	display: none;
}
</style>
<script type="text/javascript">
    jQuery( document ).ready( function() {
		jQuery( '#empty' ).click( function() {
			if( confirm( '确定要清空数据吗？点击确定后保存设置才会有效！' ) ) {
				jQuery( '.form-table input' ).attr( 'value', '' );
				jQuery( '.form-table textarea' ).attr( 'value', '' );
			} else {
			}
		});
		
		jQuery( '#generate' ).click( function() {
			var ad_pic = jQuery( '#ad-pic' ).attr( 'value' );
			if( ad_pic ) {
				var ad_link = jQuery( '#ad-link' ).attr( 'value' );
				var ad_alt = jQuery( '#ad-alt' ).attr( 'value' );
				var outcode = '<div class="ad">';
				if( ad_link )
					outcode += '<a href="' + ad_link + '" target="_blank">';
				
				outcode += '<img src="' + ad_pic + '" alt="' + ad_alt + '" />';
				
				if( ad_link )
					outcode += '</a>';
				outcode += '</div>';
				jQuery( '#code' ).attr( 'value', outcode );
				jQuery( '#generate-code' ).slideDown();
			}
		});
	});
</script>
<div class="wrap">
	<h2>WordPress广告管理</h2>
	<form method="post" action="">
		<?php
			$ads = get_option( 'ad' );
			$ads = unserialize( $ads );
			if( ! empty( $ads ) ) {
				foreach( $ads as $key=>$val ) {
					echo '<table class="form-table' . ( $val['cycle'] == 'overdue' ? ' overdue' : '' ) . '"><tbody>';
					bzg_ad_option( $key, $val );
					echo '</tbody></table>';
				}
			}
			$new_key = current_time( 'timestamp' );
			$new_val = array(
				'title' => '',
				'cycle' => '',
				'code' => '',
			);
			echo '<input type="hidden" name="new_key" value="' . $new_key . '" />';
			echo '<table class="form-table"><tbody>';
			bzg_ad_option( $new_key, $new_val );
			echo '</tbody></table>';
		?>

		<p>
			<input class="button-primary" type="submit" value="保存设置" />
			<input type="hidden" name="action" value="save" />
			<input id="empty" class="button" type="button" value="清空数据" />
		</p>

	</form>
	
	<h3>生成广告代码</h3>
	<p class="description">这个小工具可以帮助你生成广告代码</p>
	<table class="form-table">
		<tbody>
			<tr>
				<th scope="row">图片地址</th>
				<td>
					<input id="ad-pic" type="text" class="regular-text code" value="" />
				</td>
			</tr>
			<tr>
				<th scope="row">图片链接</th>
				<td>
					<input id="ad-link" type="text" class="regular-text code" value="" />
				</td>
			</tr>
			<tr>
				<th scope="row">图片描述</th>
				<td>
					<input id="ad-alt" type="text" class="regular-text code" value="" />
				</td>
			</tr>
		</tbody>
	</table>
	<p><input id="generate" class="button" type="button" value="生成代码" /></p>
	<table id="generate-code" class="form-table">
		<tbody>
			<tr>
				<th scope="row">广告代码</th>
				<td><textarea id="code" class="large-text code" rows="5" cols="50"></textarea></td>
			</tr>
		</tbody>
	</table>
</div>

<?php
} 
//添加菜单
function bzg_ad_menu() {
	if ( function_exists( 'add_options_page' ) )
		add_options_page( 'WordPress广告管理', '广告管理', 'administrator', 'ad-manage', 'bzg_ad_control' );
}
add_action( 'admin_menu', 'bzg_ad_menu' );

function bzg_ad_settings_link( $action_links, $plugin_file ) {
	if( $plugin_file == plugin_basename( __FILE__ ) ){
		$ad_settings_link = '<a href="options-general.php?page=ad-manage">设置</a>';
		array_unshift( $action_links, $ad_settings_link );
	}
	return $action_links;
}
add_filter( 'plugin_action_links', 'bzg_ad_settings_link', 10, 2 );
?>
